package com.xiyue.server.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sport.common.utils.PasswordUtils;
import com.sport.common.web.model.Result;
import com.sport.model.entity.SysUser;
import com.sport.model.vo.LoginVo;
import com.xiyue.server.annotation.RestControllerMapping;
import com.xiyue.server.service.SysUserService;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Tag(name = "登录管理器")
@RestControllerMapping("login")
public class LoginController {
    @Resource
    private SysUserService sysUserService;

    /**
     *  SaIgnore
     *      SaToken框架中自己实现了一个HandlerInterceptor
     *          判断是否开启注解isAnnotation == true? 是就放行
     */

    @SaIgnore
    @PostMapping("username")
    @Operation(summary = "账号密码登录")
    public Result<Map<String, String>> login(@RequestBody LoginVo loginVo) {
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, loginVo.getUsername()));
        if(user == null) {
            return Result.error("账号不存在或账号输入有误");
        }
        String password = user.getPassword();
        String salt = user.getSalt();
        String decryptPassword = PasswordUtils.decrypt(salt, password);
        log.info("——————————————解密前{}————————解密后{}", password, decryptPassword);

        if(loginVo.getPassword().equals(decryptPassword)) {
            StpUtil.login(user.getId());
            Map<String, String> map = new HashMap<>();
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            map.put("tokenHead", tokenInfo.tokenName);
            map.put("token", tokenInfo.tokenValue);
            return Result.success(map);
        }
        return Result.error("账号密码错误");
    }

    @GetMapping("logout")
    @Operation(summary = "退出登录")
    public Result<Boolean> logout(){
        StpUtil.logout();
        return Result.success();
    }

//    @Hidden
    @GetMapping("test")
    @Operation(summary = "测试登录后方法放不放行")
    @SaCheckPermission("login:test")
    public Result<String> test(){
        return Result.success("Hello World");
    }


}
